package com.clearliang.alarmnotice.service;

import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clearliang.alarmnotice.bean.AlarmBean;
import com.clearliang.alarmnotice.utils.AlarmUtil;

import java.util.List;

import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM;
import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM_DETAILS;

/**
 * Created by ClearLiang on 2019/2/28
 * <p>
 * Function :
 */
public class MyService extends Service {
    private AlertDialog.Builder builder;
    CountDownTimer timer;

    private void showConfirmDialog(Context context) {
        builder = new AlertDialog.Builder(context.getApplicationContext());
        builder.setTitle("提示")
                .setMessage("将在30秒后关机")
                .setCancelable(false)
                .setPositiveButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (timer != null) timer.cancel();
                            }
                        });
        setShowDialogType(context.getApplicationContext(), builder.create());
    }

    private void setShowDialogType(Context context, AlertDialog alertDialog) {
        int type;
        if (Build.VERSION.SDK_INT > 24) {
            type = WindowManager.LayoutParams.TYPE_PHONE;
        } else if (Build.VERSION.SDK_INT > 18) {
            type = WindowManager.LayoutParams.TYPE_TOAST;
        } else {
            type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        alertDialog.getWindow().setType(type);
        alertDialog.show();
        //开启倒计时，并设置倒计时时间（秒）
        startCountDownTimer(context, alertDialog, 30);
    }

    private void startCountDownTimer(final Context context, final AlertDialog alertDialog, int time) {
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //倒计时提示文字
                LogUtils.e("onTick time :" + millisUntilFinished);
                alertDialog.setMessage("将在" + (millisUntilFinished / 1000) + "关机");
            }

            @Override
            public void onFinish() {
                //倒计时结束
                LogUtils.e("倒计时结束！");
                alertDialog.dismiss();
                //倒计时结束执行定时的任务
                shutDown(context);
            }
        };
        timer.start();
    }

    //shoutDown需要系统权限才能执行否则会提示权限异常
    public void shutDown(Context context) {
        String action = "android.intent.action.ACTION_REQUEST_SHUTDOWN";
        String extraName = "android.intent.extra.USER_REQUESTED_SHUTDOWN";
        Intent intent = new Intent(action);
        intent.putExtra(extraName, true);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static final String TAG = "MyService";

    private MyBinder mBinder = new MyBinder();

    private List<AlarmBean> alarmBeanList;
    private boolean isCanStart = false;     //是否可以开启任务时钟
    private boolean isAgain = true;         //是否重复
    //long interval = AlarmManager.INTERVAL_DAY;
    long interval = 60 * 1000;              //时间间隔
    private Context context;

    //创建服务时调用
    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        //LogUtils.e("onCreate");
        String alarmDetails = SPUtils.getInstance(SP_ALARM).getString(SP_ALARM_DETAILS, "");
        if (TextUtils.isEmpty(alarmDetails)) {
            isCanStart = false;
        } else {
            alarmBeanList = JSON.parseArray(alarmDetails, AlarmBean.class);
            isCanStart = true;
        }
    }

    //服务执行的操作
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String msg = intent.getExtras().getString("alarmList");
        LogUtils.e("onStartCommand" + msg);
        return super.onStartCommand(intent, flags, startId);
    }

    //销毁服务时调用
    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.e("onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    //MyBinder类，继承Binder：让里面的方法执行下载任务，并获取下载进度
    public class MyBinder extends Binder {

        public void startAlarm() {
            // 执行具体的任务
            if (isCanStart) {
                for (int i = 0; i < alarmBeanList.size(); i++) {
                    String startTime = alarmBeanList.get(i).getStartTime();
                    String endTime = alarmBeanList.get(i).getEndTime();
                    //任务设置的时间
                    final long triggerAtMillisStart = TimeUtils.getTimeSpan(startTime, TimeUtils.getNowString(), TimeConstants.MSEC);
                    //任务设置的时间
                    final long triggerAtMillisEnd = TimeUtils.getTimeSpan(endTime, TimeUtils.getNowString(), TimeConstants.MSEC);
                    LogUtils.e(triggerAtMillisStart / 1000 + "秒", triggerAtMillisEnd / 1000 + "秒");
                    // 开始时间未到，启动两个时间任务：一个开始、一个结束
                    if (triggerAtMillisStart > 0) {
                        AlarmUtil alarmUtil1 = new AlarmUtil();
                        alarmUtil1.setAlarmTime(context.getApplicationContext(), triggerAtMillisStart, 1, true);
                        alarmUtil1.setAlarmTime(context.getApplicationContext(), triggerAtMillisEnd, 2, true);
                        //AlarmUtil alarmUtil2 = new AlarmUtil();
                        //alarmUtil2.setAlarmTime(context.getApplicationContext(), triggerAtMillisEnd, 2);

                    } else if (triggerAtMillisEnd > 0) {
                        AlarmUtil alarmUtil = new AlarmUtil();
                        alarmUtil.setAlarmTime(context.getApplicationContext(), triggerAtMillisStart, 0, true);
//                        while (isAgain) {
//                            alarmUtil.setAlarmTime(context.getApplicationContext(), triggerAtMillisEnd, 0);
//                        }
                    } else {
                        ToastUtils.showShort(alarmBeanList.get(i).getName() + " - 该时间任务已经过时");
                    }
                }
            } else {
                LogUtils.e("数据为空,开启失败");
                ToastUtils.showShort("数据为空,开启失败");
            }
        }

        public void stopAlarm() {
            LogUtils.e("stopAlarm() executed");
            // 执行具体的任务
            isCanStart = false;
            isAgain = false;
            alarmBeanList.clear();
        }

    }

}
